package com.farm.project.service.impl;

import com.farm.project.domain.Field;
import com.farm.project.domain.FieldReTtype;
import com.farm.project.domain.Project;
import com.farm.project.domain.ProjectFieldins;
import com.farm.project.domain.ProjectGradation;
import com.farm.project.domain.Task;
import com.farm.project.domain.TaskFile;
import com.farm.project.domain.TaskLog;
import com.farm.project.domain.TaskType;
import com.farm.core.time.TimeTool;
import com.farm.file.WdapFileServiceInter;
import com.farm.file.domain.FileBase;
import com.farm.file.domain.ex.PersistFile;
import com.farm.file.util.FarmDocFiles;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.farm.project.dao.FieldDaoInter;
import com.farm.project.dao.FieldReTtypeDaoInter;
import com.farm.project.dao.ProjectDaoInter;
import com.farm.project.dao.ProjectFieldinsDaoInter;
import com.farm.project.dao.ProjectGradationDaoInter;
import com.farm.project.dao.TaskDaoInter;
import com.farm.project.dao.TaskFileDaoInter;
import com.farm.project.dao.TaskLogDaoInter;
import com.farm.project.dao.TaskTypeDaoInter;
import com.farm.project.service.ProjectFieldinsServiceInter;
import com.farm.project.service.TaskServiceInter;
import com.farm.project.service.utils.IndexUtils;
import com.farm.project.service.utils.TaskFileIndexInfo;
import com.farm.view.WdapViewServiceInter;
import com.farm.web.WebUtils;
import com.farm.core.sql.query.DBRule;
import com.farm.core.sql.query.DBRuleList;
import com.farm.core.sql.query.DBSort;
import com.farm.core.sql.query.DataQuery;
import com.farm.core.sql.result.DataResult;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import com.farm.core.auth.domain.LoginUser;

/* *
 *功能：任务服务层实现类
 *详细：
 *
 *版本：v0.1
 *作者：FarmCode代码工程
 *日期：20150707114057
 *说明：
 */
@Service
public class TaskServiceImpl implements TaskServiceInter {
	@Resource
	private TaskDaoInter taskDaoImpl;
	@Resource
	private ProjectGradationDaoInter projectgradationDaoImpl;
	@Resource
	private TaskTypeDaoInter tasktypeDaoImpl;
	@Resource
	private TaskFileDaoInter taskfileDaoImpl;
	@Resource
	private TaskLogDaoInter tasklogDaoImpl;
	@Resource
	private WdapFileServiceInter wdapFileServiceImpl;
	@Resource
	private WdapViewServiceInter wdapViewServiceImpl;
	@Resource
	private ProjectDaoInter projectDaoImpl;
	@Resource
	private FieldReTtypeDaoInter fieldrettypeDaoImpl;
	@Resource
	private FieldDaoInter fieldDaoImpl;
	@Resource
	private ProjectFieldinsDaoInter projectfieldinsDaoImpl;
	@Resource
	private ProjectFieldinsServiceInter projectFieldinsServiceImpl;
	private static final Logger log = Logger.getLogger(TaskServiceImpl.class);

	@Override
	@Transactional
	public Task insertTaskEntity(Task entity, LoginUser user) {
		entity.setCuser(user.getId());
		entity.setCtime(TimeTool.getTimeDate14());
		entity.setEuser(user.getId());
		entity.setEtime(TimeTool.getTimeDate14());
		if (StringUtils.isBlank(entity.getUserid())) {
			entity.setUserid(user.getId());
		}
		ProjectGradation gradation = projectgradationDaoImpl.getEntity(entity.getGradationid());
		entity.setGradationname(gradation.getName());
		TaskType tasktype = tasktypeDaoImpl.getEntity(entity.getTasktypeid());
		entity.setTasktypename(tasktype.getName());
		initDoTime(entity);
		return taskDaoImpl.insertEntity(entity);
	}

	/**
	 * 格式化实际执行时间
	 * 
	 * @param entity
	 */
	private void initDoTime(Task entity) {
		// 1.计划，2开始，3处理，4结束,5关闭,0删除
		// 实际开始时间 DOSTIME//3处理，4结束,5关闭
		if (StringUtils.isBlank(entity.getDostime()) && (entity.getPstate().equals("3")
				|| entity.getPstate().equals("4") || entity.getPstate().equals("5"))) {
			if (StringUtils.isBlank(entity.getDoetime())) {
				// 已经结束
				entity.setDostime(TimeTool.getTimeDate14());
			} else {
				// 未结束
				entity.setDostime(entity.getDoetime());
			}
		}
		// 实际结束时间 DOETIME//4结束,5关闭
		if (StringUtils.isBlank(entity.getDoetime())
				&& (entity.getPstate().equals("4") || entity.getPstate().equals("5"))) {
			entity.setDoetime(TimeTool.getTimeDate14());
		}
	}

	@Override
	@Transactional
	public Task editTaskEntity(Task entity, LoginUser user) {
		Task entity2 = taskDaoImpl.getEntity(entity.getId());
		entity2.setTitle(entity.getTitle());
		entity2.setPstate(entity.getPstate());
		entity2.setCompletion(entity.getCompletion());
		entity2.setDotimes(entity.getDotimes());
		entity2.setUserid(entity.getUserid());
		entity2.setPcontent(entity.getPcontent());
		entity.setEuser(user.getId());
		entity.setEtime(TimeTool.getTimeDate14());
		initDoTime(entity);
		taskDaoImpl.editEntity(entity2);
		return entity2;
	}

	@Override
	@Transactional
	public void deleteTaskEntity(String id, LoginUser user) {
		taskfileDaoImpl.deleteEntitys(DBRuleList.getInstance().add(new DBRule("TASKID", id, "=")).toList());
		tasklogDaoImpl.deleteEntitys(DBRuleList.getInstance().add(new DBRule("TASKID", id, "=")).toList());
		taskDaoImpl.deleteEntity(taskDaoImpl.getEntity(id));
	}

	@Override
	@Transactional
	public Task getTaskEntity(String id) {
		if (id == null) {
			return null;
		}
		return taskDaoImpl.getEntity(id);
	}

	@Override
	@Transactional
	public DataQuery createTaskSimpleQuery(DataQuery query) {
		query.addRule(new DBRule("a.PSTATE", "0", "!="));
		DataQuery dbQuery = DataQuery.init(query,
				"PLOGS_TASK A LEFT JOIN ALONE_AUTH_USER B ON A.USERID=B.ID LEFT JOIN PLOGS_PROJECT C ON A.PROJECTID=C.ID LEFT JOIN ALONE_AUTH_USER D ON A.CUSER=D.ID",
				"A.ID AS ID,A.TITLE AS TITLE,A.TASKTYPENAME AS TASKTYPENAME,B.NAME AS USERNAME,A.PSTATE AS PSTATE,C.NAME AS PROJECTNAME,PLANSTIME,A.GRADATIONNAME AS GRADATIONNAME,DOSTIME,DOTIMES,SOURCEUSERID,D.NAME AS CUSERNAME");
		return dbQuery;
	}

	@Override
	@Transactional
	public List<Map<String, Object>> getTasks(LoginUser currentUser) throws SQLException {
		return getTasks(currentUser, null, null);
	}

	@Override
	@Transactional
	public void editTaskState(String taskId, String state, LoginUser currentUser) {
		Task task = taskDaoImpl.getEntity(taskId);
		task.setPstate(state);
		task.setEtime(TimeTool.getTimeDate14());
		task.setEuser(currentUser.getId());
		initDoTime(task);
		if (state.equals("3")) {
			task.setDostime(TimeTool.getTimeDate14());
		}
		if (state.equals("4")) {
			task.setCompletion(100);
			task.setDoetime(TimeTool.getTimeDate14());
		}
		taskDaoImpl.editEntity(task);
		stateHandle(task);
	}

	@Override
	@Transactional
	public void closeTask(String taskId, LoginUser currentUser) {
		Task task = taskDaoImpl.getEntity(taskId);
		task.setPstate("5");
		task.setEtime(TimeTool.getTimeDate14());
		task.setEuser(currentUser.getId());
		initDoTime(task);
		task.setDoetime(TimeTool.getTimeDate14());
		taskDaoImpl.editEntity(task);
		stateHandle(task);
	}

	/**
	 * 处理全文索引
	 * 
	 * @param task
	 */
	private void stateHandle(Task task) {
		if (task.getPstate().equals("5")) {
			List<TaskFile> files = taskfileDaoImpl
					.selectEntitys(DBRuleList.getInstance().add(new DBRule("TASKID", task.getId(), "=")).toList());
			for (TaskFile node : files) {
				IndexUtils.indexTaskFile(getIndexInfo(node.getId()));
			}
		}
	}

	@Override
	@Transactional
	public Task addTask(String title, String projectid, String gradationid, String tasktypeid, String state,
			String planetime, String text, LoginUser currentUser) throws IOException {
		Task task = new Task();
		task.setTitle(title);
		task.setProjectid(projectid);
		task.setGradationid(gradationid);
		task.setTasktypeid(tasktypeid);
		task.setPstate(state);
		if (StringUtils.isNotBlank(planetime)) {
			task.setPlanetime(planetime);
		}
		task = insertTaskEntity(task, currentUser);
		loadTaskField(task.getId(), currentUser);
		if (StringUtils.isNotBlank(text)) {
			// 处理超文本中附件
			List<FileBase> files = prisistTextFiles(text);
			// 处理超文本
			FileBase file = prisistTextToFile(task.getReadfileid(), text, "任务描述" + ".ihtml", currentUser);
			insertTaskFile(file.getId(), task, "任务描述", "1", null);
			for (FileBase node : files) {
				insertTaskFile(node.getId(), task, "描述附件", "2", null);
			}
			files.add(file);
			for (FileBase node : files) {
				wdapFileServiceImpl.submitFile(node.getId());
				if (wdapViewServiceImpl.fileConvertAble(node.getExname(), node.getFilesize())) {
					// 可以预览
					wdapViewServiceImpl.reLoadFileViewTask(node.getId());
				}
			}
			task.setReadfileid(file.getId());
			initDoTime(task);
			taskDaoImpl.editEntity(task);
		}
		return task;
	}

	@Override
	@Transactional
	public void loadTaskField(String taskid, LoginUser currentUser) {
		// 通过项目分类id获得项目的属性
		Task task = taskDaoImpl.getEntity(taskid);
		Project project = projectDaoImpl.getEntity(task.getProjectid());
		List<FieldReTtype> fieldRes = fieldrettypeDaoImpl.selectEntitys(
				DBRuleList.getInstance().add(new DBRule("TASKTYPEID", task.getTasktypeid(), "=")).toList());
		for (FieldReTtype para : fieldRes) {
			// 属性定义
			Field field = fieldDaoImpl.getEntity(para.getFieldid());
			if (field.getPstate().equals("1")) {
				// 项目属性实例
				ProjectFieldins fieldIns = projectfieldinsDaoImpl.getOneEntityByUUID(project.getId(), field.getUuid());
				if (fieldIns == null) {
					fieldIns = new ProjectFieldins();
					fieldIns.setPubread("0");
				}
				fieldIns.setValtype(field.getValtype());
				fieldIns.setName(field.getName());
				fieldIns.setEnums(field.getEnums());
				fieldIns.setUuid(field.getUuid());
				fieldIns.setSort(field.getSort());
				fieldIns.setProjectid(project.getId());
				fieldIns.setPstate("1");
				fieldIns.setSingletype(field.getSingletype());
				if (fieldIns.getId() == null) {
					projectFieldinsServiceImpl.insertProjectfieldinsEntity(fieldIns, currentUser);
				} else {
					projectfieldinsDaoImpl.editEntity(fieldIns);
				}
			}
		}
	}

	/**
	 * 创建一个任务的关联附件
	 * 
	 * @param fileid     附件id
	 * @param task       任务
	 * @param fieldName  附件名称
	 * @param sourceType 来源类型1.任务描述,2.任务描述附件，3.任务日志，4任务日志附件
	 * @param log        日志（非日志附件可以为空）
	 */
	private void insertTaskFile(String fileid, Task task, String fieldName, String sourceType, TaskLog log) {
		taskfileDaoImpl.deleteEntitys(DBRuleList.getInstance().add(new DBRule("FILEID", fileid, "="))
				.add(new DBRule("TASKID", task.getId(), "=")).toList());
		TaskFile tfile = new TaskFile();
		tfile.setCtime(TimeTool.getTimeDate14());
		tfile.setFileid(fileid);
		tfile.setSourcetype(sourceType);
		if (log != null) {
			tfile.setLogid(log.getId());
		}
		tfile.setTaskid(task.getId());
		taskfileDaoImpl.insertEntity(tfile);
	}

	/**
	 * 持久化富文本中的附件
	 * 
	 * @param text
	 * @throws FileNotFoundException
	 */
	private List<FileBase> prisistTextFiles(String text) throws FileNotFoundException {
		if (StringUtils.isBlank(text)) {
			return new ArrayList<>();
		}
		List<FileBase> backfiles = new ArrayList<>();
		List<String> files = FarmDocFiles.getFilesIdFromHtml(text);
		for (String fileid : files) {
			backfiles.add(wdapFileServiceImpl.getFileBase(fileid));
		}
		return backfiles;
	}

	/**
	 * 保存富文本为一个文件对象
	 * 
	 * @param fileId      為空時創建，不爲空時修改
	 * @param text
	 * @param fileName
	 * @param currentUser
	 * @return
	 * @throws IOException
	 */
	private FileBase prisistTextToFile(String fileId, String text, String fileName, LoginUser currentUser)
			throws IOException {
		FileBase file = null;
		if (StringUtils.isNotBlank(fileId)) {
			// 更新文件
			file = wdapFileServiceImpl.getFileBase(fileId);
			wdapFileServiceImpl.updateFilesize(fileId, text.length());
		}
		if (file == null) {
			// 创建文件
			file = wdapFileServiceImpl.initFile(currentUser, fileName, text.length(), null, "PLOGS");
		}
		wdapFileServiceImpl.WriteTextFile(file.getId(), text, currentUser);
		return file;
	}

	@Override
	@Transactional
	public String readText(String fileid) {
		PersistFile pfile = wdapFileServiceImpl.getPersistFile(fileid);
		String text = FarmDocFiles.readFileText(pfile.getFile());
		return text;
	}

	@Override
	@Transactional
	public Task updateTask(String taskid, String title, String projectid, String gradationid, String tasktypeid,
			String state, String planetime, String text, LoginUser currentUser) throws IOException, SQLException {
		Task task = taskDaoImpl.getEntity(taskid);
		task.setTitle(title);
		task.setProjectid(projectid);
		task.setGradationid(gradationid);
		task.setGradationname(projectgradationDaoImpl.getEntity(gradationid).getName());
		task.setTasktypeid(tasktypeid);
		task.setTasktypename(tasktypeDaoImpl.getEntity(tasktypeid).getName());
		task.setPstate(state);
		if (StringUtils.isNotBlank(planetime)) {
			task.setPlanetime(planetime);
		}
		task.setEtime(TimeTool.getTimeDate14());
		task.setEuser(currentUser.getId());
		initDoTime(task);
		taskDaoImpl.editEntity(task);
		if (StringUtils.isNotBlank(text)) {
			// 处理超文本中附件
			List<FileBase> files = prisistTextFiles(text);
			// 处理超文本
			FileBase file = prisistTextToFile(task.getReadfileid(), text, title + ".ihtml", currentUser);
			insertTaskFile(file.getId(), task, "任务描述", "1", null);
			Set<String> hasFilesDic = new HashSet<>();
			for (FileBase node : files) {
				// 保存任务描述中的附件
				insertTaskFile(node.getId(), task, "描述附件", "2", null);
				hasFilesDic.add(node.getId());
			}
			for (Map<String, Object> node : taskfileDaoImpl.getTaskReadFiles(taskid)) {
				// 删除任务描述中失效附件
				if (!hasFilesDic.contains(node.get("FILEID"))) {
					taskfileDaoImpl.deleteEntity(taskfileDaoImpl.getEntity((String) node.get("ID")));
				}
			}
			files.add(file);
			for (FileBase node : files) {
				wdapFileServiceImpl.submitFile(node.getId());
				if (wdapViewServiceImpl.fileConvertAble(node.getExname(), node.getFilesize())) {
					// 可以预览
					wdapViewServiceImpl.reLoadFileViewTask(node.getId());
				}
			}
			task.setReadfileid(file.getId());
			initDoTime(task);
			taskDaoImpl.editEntity(task);
		}
		return task;
	}

	@Override
	@Transactional
	public TaskLog saveLog(String taskid, String text, LoginUser currentUser) throws IOException, SQLException {
		if (text == null || text.trim().length() <= 0) {
			return null;
		}
		TaskLog log = getTodayLog(taskid);
		Task task = taskDaoImpl.getEntity(taskid);
		task.setEtime(TimeTool.getTimeDate14());
		taskDaoImpl.editEntity(task);
		FileBase logfile = null;
		if (log == null) {
			String logFileName = "任务日志-" + TimeTool.format(new Date(), "yyyy年MM月dd日") + ".ihtml";
			String todayKey = TimeTool.format(new Date(), "yyyyMMdd");
			logfile = prisistTextToFile(null, text, logFileName, currentUser);
			log = new TaskLog();
			log.setCtime(TimeTool.getTimeDate14());
			log.setCuser(currentUser.getId());
			log.setDatekey(todayKey);
			log.setEtime(TimeTool.getTimeDate14());
			log.setEuser(currentUser.getId());
			log.setFileid(logfile.getId());
			log.setTaskid(task.getId());
			tasklogDaoImpl.insertEntity(log);
		} else {
			log.setEtime(TimeTool.getTimeDate14());
			log.setEuser(currentUser.getId());
			tasklogDaoImpl.editEntity(log);
			logfile = prisistTextToFile(log.getFileid(), text, null, currentUser);
		}
		// 处理超文本中附件
		List<FileBase> files = prisistTextFiles(text);
		// 处理超文本
		insertTaskFile(logfile.getId(), task, "任务日志", "3", log);
		Set<String> hasFilesDic = new HashSet<>();
		for (FileBase node : files) {
			// 保存日志中的附件
			insertTaskFile(node.getId(), task, "日志附件", "4", log);
			hasFilesDic.add(node.getId());
		}
		for (Map<String, Object> node : taskfileDaoImpl.getLogFiles(log.getId())) {
			// 删除日志中失效附件
			if (!hasFilesDic.contains(node.get("FILEID"))) {
				taskfileDaoImpl.deleteEntity(taskfileDaoImpl.getEntity((String) node.get("ID")));
			}
		}
		files.add(logfile);
		for (FileBase node : files) {
			wdapFileServiceImpl.submitFile(node.getId());
			if (wdapViewServiceImpl.fileConvertAble(node.getExname(), node.getFilesize())) {
				// 可以预览
				wdapViewServiceImpl.reLoadFileViewTask(node.getId());
			}
		}
		return log;
	}

	@Override
	@Transactional
	public TaskLog getTodayLog(String taskid) {
		String todayKey = TimeTool.format(new Date(), "yyyyMMdd");
		List<TaskLog> log = tasklogDaoImpl.selectEntitys(DBRuleList.getInstance()
				.add(new DBRule("DATEKEY", todayKey, "=")).add(new DBRule("TASKID", taskid, "=")).toList());
		return log.size() > 0 ? log.get(0) : null;
	}

	@Override
	@Transactional
	public String getlog(String taskid) {
		TaskLog log = getTodayLog(taskid);
		if (log != null) {
			return readText(log.getFileid());
		} else {
			return "";
		}
	}

	@Override
	@Transactional
	public List<Map<String, Object>> getTasks(LoginUser currentUser, String states, String title) throws SQLException {
		DataQuery dbQuery = DataQuery.init(new DataQuery(),
				"PLOGS_TASK a left join PLOGS_TASK_USER g on a.id=g.TASKID left join PLOGS_PROJECT b on a.projectid=b.id left join PLOGS_RE_VIEWTASK c on c.TASKID=a.ID and c.USERID='"
						+ currentUser.getId()
						+ "' left join  PLOGS_PROJECT_RE_COMPANY d on d.projectid=b.id left join PLOGS_PROJECT_COMPANY e on e.id=d.companyid",
				"a.id as ID,c.VIEWID as VIEWID,a.PLANETIME as PLANETIME,a.TITLE as TITLE,a.PSTATE as PSTATE,a.SOURCEUSERID as SOURCEUSERID,a.GRADATIONNAME as GRADATIONNAME,a.GRADATIONID as GRADATIONID,a.TASKTYPENAME as TASKTYPENAME,a.TASKTYPEID as TASKTYPEID,e.name as COMPANYNAME"
						+ ",b.NAME as PROJECTNAME");
		dbQuery.addRule(new DBRule("g.USERID", currentUser.getId(), "="));
		// dbQuery.addRule(new DBRule("a.USERID", currentUser.getId(), "="));

		if (StringUtils.isNotBlank(title)) {
			dbQuery.addSqlRule("and (b.NAME like '%" + title + "%' or E.NAME  like '%" + title + "%')");
		}
		// dbQuery.addSqlRule(" and (b.STATE='1' or b.STATE='0')");
		if (StringUtils.isNotBlank(states)) {
			String stateRuleSql = null;
			for (String state : WebUtils.parseIds(states)) {
				if (stateRuleSql == null) {
					stateRuleSql = "a.PSTATE='" + state + "'";
				} else {
					stateRuleSql = stateRuleSql + " or a.PSTATE='" + state + "'";
				}
			}
			dbQuery.addSqlRule("and (" + stateRuleSql + ")");
		} else {
			dbQuery.addRule(new DBRule("a.PSTATE", "5", "!="));
		}
		dbQuery.setPagesize(1000);
		dbQuery.setNoCount();
		dbQuery.setDefaultSort(new DBSort("a.CTIME", "ASC"));
		DataResult result = dbQuery.search();
		return result.getResultList();
	}

	@Override
	@Transactional
	public int getTaskCount(LoginUser currentUser, String state) {
		return taskDaoImpl.getTaskNum(currentUser.getId(), state);
	}

	@Override
	@Transactional
	public List<TaskLog> getLogs(String taskId) {
		List<TaskLog> logs = tasklogDaoImpl
				.selectEntitys(DBRuleList.getInstance().add(new DBRule("TASKID", taskId, "=")).toList());
		Collections.sort(logs, new Comparator<TaskLog>() {
			@Override
			public int compare(TaskLog o1, TaskLog o2) {
				return o1.getDatekey().compareTo(o2.getDatekey());
			}
		});
		for (TaskLog log : logs) {
			if (StringUtils.isNotBlank(log.getFileid())) {
				log.setText(readText(log.getFileid()));
			}
		}
		return logs;
	}

	@Override
	@Transactional
	public DataQuery createTaskfileSimpleQuery(DataQuery query) {
		DataQuery dbQuery = DataQuery.init(query,
				"PLOGS_TASK_FILE a LEFT JOIN plogs_task b ON b.id = a.TASKID LEFT JOIN WDAP_FILE c ON c.id = a.FILEID",
				"a.ID as ID,a.FILEID as FILEID,c.TITLE AS FILENAME,a.SOURCETYPE as SOURCETYPE, a.CTIME AS CTIME, b.TITLE AS TASKNAME");
		return dbQuery;
	}

	@Override
	@Transactional
	public TaskFile editTaskfileEntity(TaskFile entity, LoginUser user) {
		TaskFile entity2 = taskfileDaoImpl.getEntity(entity.getId());
		taskfileDaoImpl.editEntity(entity2);
		return entity2;
	}

	@Override
	@Transactional
	public void deleteTaskfileEntity(String id, LoginUser user) {
		taskfileDaoImpl.deleteEntity(taskfileDaoImpl.getEntity(id));
	}

	@Override
	@Transactional
	public TaskFile getTaskfileEntity(String id) {
		if (id == null) {
			return null;
		}
		return taskfileDaoImpl.getEntity(id);
	}

	@Override
	@Transactional
	public List<TaskFile> getTaskfiles(String taskid) {
		List<TaskFile> files = taskfileDaoImpl
				.selectEntitys(DBRuleList.getInstance().add(new DBRule("TASKID", taskid, "=")).toList());
		for (TaskFile file : files) {
			file.setFile(wdapFileServiceImpl.getFileBase(file.getFileid()));
		}
		return files;
	}

	@Override
	@Transactional
	public TaskFileIndexInfo getIndexInfo(String taskfileid) {
		TaskFileIndexInfo indexInfo = new TaskFileIndexInfo();
		indexInfo.setTaskfile(taskfileDaoImpl.getEntity(taskfileid));
		indexInfo.setFile(wdapFileServiceImpl.getFileBase(indexInfo.getTaskfile().getFileid()));
		indexInfo.setText(wdapFileServiceImpl.getFiletext(indexInfo.getTaskfile().getFileid()));
		indexInfo.setTask(taskDaoImpl.getEntity(indexInfo.getTaskfile().getTaskid()));
		indexInfo.setProject(projectDaoImpl.getEntity(indexInfo.getTask().getProjectid()));
		return indexInfo;
	}

	@Override
	@Transactional
	public List<TaskFileIndexInfo> getIndexInfos(String fileid) {
		List<TaskFile> taskfiles = taskfileDaoImpl
				.selectEntitys(DBRuleList.getInstance().add(new DBRule("FILEID", fileid, "=")).toList());
		List<TaskFileIndexInfo> infos = new ArrayList<>();
		for (TaskFile taskfile : taskfiles) {
			infos.add(getIndexInfo(taskfile.getId()));
		}
		return infos;
	}

	@Override
	@Transactional
	public DataQuery getTaskQuery(String stime, String etime) {
		String logRule="";
		if (StringUtils.isNotBlank(stime) && StringUtils.isNotBlank(etime)) {
			stime = (stime.trim().replace("-", "") + "0000000000000000").substring(0, 14);
			etime = (etime.trim().replace("-", "") + "9999999999999999").substring(0, 14);
			logRule="AND F.ETIME > '"+stime+"' AND F.ETIME < '"+etime+"'";
		}
		if (StringUtils.isNotBlank(stime) && StringUtils.isBlank(etime)) {
			stime = (stime.trim().replace("-", "") + "0000000000000000").substring(0, 14);
			logRule="AND F.ETIME > '"+stime+"'";
		}
		if (StringUtils.isBlank(stime) && StringUtils.isNotBlank(etime)) {
			etime = (etime.trim().replace("-", "") + "9999999999999999").substring(0, 14);
			logRule=" AND F.ETIME < '"+etime+"'";
		}
		DataQuery dbQuery = DataQuery.init(new DataQuery(),
				"PLOGS_TASK A  LEFT JOIN PLOGS_TASK_USER G ON G.TASKID=A.ID LEFT JOIN PLOGS_PROJECT B ON A.PROJECTID = B.ID LEFT JOIN PLOGS_PROJECT_RE_COMPANY C ON C.PROJECTID = B.ID LEFT JOIN PLOGS_PROJECT_COMPANY D ON D.ID = C.COMPANYID LEFT JOIN ALONE_AUTH_USER E ON A.USERID=E.ID LEFT JOIN PLOGS_TASK_LOG F ON F.TASKID=A.ID "+logRule,
				"A.ID AS TASKID,B.ID AS PROJECTID,A.TITLE AS TASKTITLE, A.ETIME AS TASKETIME, B. NAME AS PROJECTNAME, D. NAME AS COMPANYNAME, E. NAME AS USERNAME, A. COMPLETION AS COMPLETION, A.DOTIMES AS DOTIMES,A.DOSTIME AS DOSTIME");
		return dbQuery;
	}

	@Override
	@Transactional
	public TaskLog getLogById(String tasklogid) {
		return tasklogDaoImpl.getEntity(tasklogid);
	}
}
